package gitobject;
import repository.Repository;
import zlib.ZLibUtils;

import java.io.*;


public class GitObject implements Serializable{

    protected String fmt;                  //type of object
    protected String key;                  //key of object
    protected String mode;                 //mode of object
    protected static String path = Repository.getGitDir() + File.separator + "objects";          //absolute path of objects
    protected String value;                //value of object
    protected File file;

    public String getFmt(){
        return fmt;
    }
    public String getKey() { return key; }
    public String getMode(){
        return mode;
    }
    public String getPath() {
        return path;
    }
    public String getValue(){
        return value;
    }
    public File getFile() { return file; }


    public GitObject(){}
    /**
     * Get the value(content) of file
     * @param file
     * @return String
     * @throws IOException
     */
    public static String getValue(File file) throws IOException {
        FileInputStream is = new FileInputStream(file);
        byte[] bytes = new byte[0];
        bytes = new byte[is.available()];
        is.read(bytes);
        String fileContents = new String(bytes);
        return fileContents;
        //return new String();
    }
    /**
     * Todo: Serialize the object to the local repository.
     * @throws Exception
     */
    public void writeObject() throws Exception{
        try {
            File parentDir = new File(path + File.separator + key.substring(0, 2));
            parentDir.mkdir();
            File file = new File(path + File.separator + key.substring(0, 2) + File.separator + key.substring(2));
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(this);
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * Todo: Serialize the object and compress with zlib.
     * @throws Exception
     */
    public void compressWrite() throws Exception{
        /**
         * Add your code here.
         */
        byte[] data = ZLibUtils.compress(value.getBytes());
        FileOutputStream fos = new FileOutputStream(path + File.separator + key);
        fos.write(data);
        fos.close();
    }

    public static void writeFile(File des, byte[] data) throws IOException {
        FileOutputStream fos = new FileOutputStream(des);
        fos.write(data);
        fos.close();

    }
}
